package com.petsbang.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;

import com.petsbang.action.LovelyActivity;
import com.petsbang.action.dao.DataApplication;

public class DetialGallery extends Gallery {
	private MotionEvent e;
	LovelyActivity activity;
	FriendlyScrollView currScrollView;
	int flingWidth;
	int flingHeight;
	boolean isScroll;
	

	public DetialGallery(Context context, AttributeSet attrSet) {
		super(context, attrSet);
		activity = (LovelyActivity) context;
		DataApplication appState = (DataApplication) context.getApplicationContext();
		flingWidth = appState.getWidth() / 5;
		flingHeight = appState.getHeight() / 5;
		
	}

	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
		return e2.getX() > e1.getX();
	}

	private boolean isScrollingDown(MotionEvent e1, MotionEvent e2) {
		return Math.abs(e2.getX() - e1.getX()) < 20 || Math.abs(e2.getY() - e1.getY()) > 30;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		int kEvent;
		if (isScroll) {
			kEvent = KeyEvent.KEYCODE_DPAD_DOWN;
			if (currScrollView != null) {
				currScrollView.fling(-(int) velocityY);
				return false;
			}
		} else 
			if (isScrollingLeft(e1, e2)) {
			kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		} else {
			kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		}
		onKeyDown(kEvent, null);
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		return super.onTouchEvent(ev);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		currScrollView = getCurrScrollView();
		boolean bb = super.onInterceptTouchEvent(ev);
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			e = MotionEvent.obtain(ev);
			super.onTouchEvent(ev);
		} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
			if (Math.abs(ev.getX() - e.getX()) > 20 || Math.abs(ev.getY() - e.getY()) > 20) {
				Log.v("","Math.abs(e2.getX() - e1.getX())"+Math.abs(ev.getX() - e.getX()));
				if (isScrollingDown(ev,e)) {
					isScroll = true;
				}else{
					isScroll = false;
				}
				bb = true;
			}
		}else if (ev.getAction() == MotionEvent.ACTION_UP) {
			isScroll = false;
		}
		return bb;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

		if (isScroll) {
			if (currScrollView != null) {
				currScrollView.scrollBy(0, (int) distanceY);
			}
			return false;
		} else {
			return super.onScroll(e1, e2, distanceX, 0);
		}

	}

	private FriendlyScrollView getCurrScrollView() {
		int pos = getFirstVisiblePosition();
		if (pos != getAdapter().getCount() - 1) {
			return (FriendlyScrollView) this.getSelectedView();
		} else {
			return null;
		}
	}
}
